<?php
/**
 * Created by PhpStorm.
 * User: 杨胜飞
 * Date: 2017\8\28 0028
 * Time: 10:43
 */

namespace app\admin\controller;



use app\common\controller\Three;
use app\common\model\Administrative;
use app\common\model\Contract;
use app\common\model\ContractEquipment;
use app\common\model\Customer;
use app\common\model\WorkEquipment;
use app\common\model\WorkOrderRemarks;
use app\common\model\Equipments;
use think\Cache;
use think\db;


/**
 * Class Workorder
 * @package app\operation\controller
 *         总后台 工单管理  控制器
 */
class Workorder extends Base
{
    // 声明一个属性 用来装模型
    protected static $workModel;

    // 初始化方法  用来实例化模型
    public function __construct()
    {
        parent::__construct();
        // 实例化工单 模型
        self::$workModel = new \app\common\model\WorkOrder();
    }

    /**
     * @return \think\response\Json
     *     获取装机型号+设备编号
     */
    public function getequipments($contractId = '')
    {
        // 获取合同id
        $contract_id = input('get.contract_id');

        // 实例化合同设备关联表模型
        $contractEquipmentModel = new ContractEquipment();
        // 查询字段
        $field = ['id,equipments_id,equipments_number'];
        // 判断是否有数据
        if (!empty($contractId)) {
            // 根据合同id查询
            $where['contract_id'] = $contractId;
        }else{
            // 根据合同id查询
            $where['contract_id'] = $contract_id;
        }

        // 调用get_id_all方法查询 获取设备id跟设备编号
        $equipment = $contractEquipmentModel->get_id_all($where,$field);

        // 实例化设备表模型
        $equipmentModel = new Equipments();
        // 查询字段
        $fields = ['equipments_id,equipments_name'];
        // 循环取出查询设备
        foreach ($equipment as $k => $v)
        {
            $equipments[] = $equipmentModel->get_id_all($v['equipments_id'],$fields);
        }
        if (!empty($equipments)) {
            // 将装机设备 跟 设备编号合并
            foreach ($equipments as $k => $v){
                foreach ($v as $key => $val){
                    // 将装机设备 跟 设备编号合并
                    $val['equipments_number'] = $equipment[$k]['equipments_number'];
                    $val['id'] = $equipment[$k]['id'];
                    $equipmentsNumber[] = $val;
                }
            }
        }else{
            $equipmentsNumber = '';
        }


        if (!empty($contractId)) {
            return $equipmentsNumber;
        }else{
            // 返回
            return json($equipmentsNumber);
        }


    }

    /**
     * @return mixed
     *      渲染工单修改页面
     */
    public function edit()
    {
        // 接收工单id
        $wid = input('')['wid'];
        // 客户id
        $uid = input('')['uid'];
        // 合同id
        $cid = input('')['cid'];
        // 判断从工单列表页，还是续费换芯页面点击的修改，1为续费页，2为换芯页，3为工单未指派页，4为工单已指派页，5为工单回收站
        $who = input('')['who'];

        // 实例化用户表模型
        $userModel = new Customer();

        // 查出工单信息，用于回显
        $where['work_order_id'] = $wid;
        $workData = self::$workModel->getOne($where);
//        dump(json_decode(json_encode($workData),true));die();

        //获取地址三级联动
        $province = $userModel->areasProvince();
        $city = $userModel->areasCity($workData['province_code']);
        $area = $userModel->areaName($workData['city_code']);

        // 获取工单业务类型
        $workType = config('workorder_type');
        // 当前工单业务类型
        $business = $workData['business_id'];

        // 当工单为新装时
        if ($workData['business_id'] == 3) {
            // 判断是否绑定合同 给他一个标识符 1为已绑定合同,0为没有绑定合同
            if ($cid == 'null') {
                // 没有绑定
                $identifier = 0;
            }else{
                // 绑定了
                $identifier = 1;
            }
        }else{
            $identifier = '';
        }

        // 查出客户信息，用于回显
        $uwhere['user_id'] = $uid;
        // 实例化用户表模型
        $userData = $userModel->selectOne($uwhere);

        // 查出合同信息，用于回显
        $cwhere['contract_id'] = $cid;
        // 实例化合同模型
        $contractModel = new Contract();
        $contractData = $contractModel->selectData($cwhere);
        foreach ($contractData as $k => $v)
        {
            $contractData[$k]['installed_time'] = date('Y/m/d',$v['installed_time']);
            $contractData[$k]['exire_date'] = date('Y/m/d',$v['exire_date']);
        }

        if (!empty($contractData)) {
            // 调用getequipments方法，获取当前合同下的所有装机型号跟设备编号
            $equipmentsNumber = $this->getequipments($contractData[0]['contract_id']);
        }
        if (empty($equipmentsNumber)) {
            $equipmentsNumber =  '';
        }
        //dump(json_decode(json_encode($equipmentsNumber),true));die();
        // 实例化工单设备关联表
        $workEquipmentModel = new WorkEquipment();
        $ewhere['work_order_id'] = $workData['work_order_id'];
        // 根据工单ID获取合同设备关联表ID
        $workEquipmentData = $workEquipmentModel->getOne($ewhere);

        // 实例化合同设备关联表模型
        $contractEquipmentModel = new ContractEquipment();
        $cewhere['id'] = $workEquipmentData['contract_equipment_id'];
        $contractEquipmentData = $contractEquipmentModel->getOne($cewhere);
        // 获取当前工单设备编号
        $equipments_number = $contractEquipmentData['equipments_number'];

        // 实例化设备表模型
        $equipmentsModel = new Equipments();
        $eqwhere['equipments_id'] = $contractEquipmentData['equipments_id'];
        $equipmentsData = $equipmentsModel->selectOne($eqwhere);
        $equipments_name = $equipmentsData['equipments_name'];


        // 调用视图,将数据赋值给页面
        return $this->fetch('edit',
            [
                'workData' => $workData,                     // 工单数据
                'userData' => $userData,                     // 客户数据
                'contractData' => $contractData,             // 合同数据
                'workType' => $workType,                     // 工单类型
                'business' => $business,                     // 当前工单类型
                'province' => $province,                     // 省
                'city' => $city,                             // 市
                'area' => $area,                             // 县
                'equipmentsNumber' => $equipmentsNumber,     // 合同下的所有装机型号+设备编号
                'equipments_number' => $equipments_number,   // 当前工单的设备编号
                'equipments_name' => $equipments_name,       // 当前工单的装机型号
                'who' => $who,                               // 页面标识数
                'identifier' => $identifier,                 // 判断有没有绑定合同标识符
            ]);

    }

    /**
     *      处理工单修改数据
     */
    public function modify()
    {
        // 端名称
        $company_name = '总后台';

        // 获取当前登录用户id
        $u_id = session($this->set['db_name'].'uid');
        // 获取当前登录用户名
        $username = session($this->set['db_name'].'username');

        // 接收修改的数据
        $data = request()->post();

        // 声明一个空数组用来装工单数据
        $workData = [];
        // 判断数据是否有值
        if (empty($data)) {
            $this->error('参数错误');
        }else{
            // 当业务类型为移机时
            if ($data['businessid'] == 5) {
                $workData['business_id'] = $data['shift'];                 // 移机类型
                $workData['isuser'] = $data['isuser'];                     // 是否同一用户
                $workData['move_province'] = $data['moveprovince'];        // 移机地址省
                $workData['move_city'] = $data['movecity'];                // 移机地址市
                $workData['move_area'] = $data['movearea'];                // 移机地址区
                $workData['move_province_code'] = $data['province_id'];    // 移机地址省id
                $workData['move_city_code'] = $data['city_id'];            // 移机地址市id
                $workData['move_area_code'] = $data['area_id'];            // 移机地址区id
                $workData['move_address'] = $data['service_address'];      // 移机地址拼接
            }else{
                $workData['business_id'] = $data['businessid'];            // 业务类型
            }
                $workData['user_id'] = $data['user_id'];                   // 用户id
                $workData['contract_id'] = $data['contract_id'];           // 合同id
                $workData['combo_money'] = $data['combo_money'];           // 费用
                $workData['update_time'] = time();                         // 更新时间
                $workData['province'] = $data['userprovince'];             // 服务地址省
                $workData['city'] = $data['usercity'];                     // 服务地址市
                $workData['area'] = $data['userarea'];                     // 服务地址区
                $workData['province_code'] = $data['province_code'];       // 服务地址省id
                $workData['city_code'] = $data['city_code'];               // 服务地址市id
                $workData['area_code'] = $data['area_code'];               // 服务地址区id
                $workData['service_address'] = $data['user_address'];      // 服务详细地址
                $workData['remarks'] = $data['remarks'] ? $data['remarks'] : '修改工单'; // 备注
                $workData['contact_number'] = $data['contact_number'];     // 下单时联系电话
                $workData['contacts'] = $data['contacts'];                 // 下单时联系人
        }
//        dump($workData);die();
        // 调用modify方法，完成一次工单修改
        $result = self::$workModel->modify($workData, $data, $u_id, $username, $company_name);
        // 1为续费页，2为换芯页，3为工单未指派页，4为工单已指派页，5为工单回收站
        if ($data['who'] == 1) {
            if ($result == false) {
                $this->error('修改失败');
            }
            $this->success('修改成功','/admin/workorder/renew');
        }
        if ($data['who'] == 2) {
            if ($result == false) {
                $this->error('修改失败');
            }
            $this->success('修改成功','/admin/workorder/core');
        }
        if ($data['who'] == 3) {
            if ($result == false) {
                $this->error('修改失败');
            }
            $this->success('修改成功','/admin/workorder/unassigned');
        }
        if ($data['who'] == 4) {
            if ($result == false) {
                $this->error('修改失败');
            }
            $this->success('修改成功','/admin/workorder/assigned');
        }
        if ($data['who'] == 5) {
            if ($result == false) {
                $this->error('修改失败');
            }
            $this->success('修改成功','/admin/workorder/recycle');
        }

    }

    /**
     * @param $workorderstatus
     * @return false|\PDOStatement|string|\think\Collection
     *        处理  (未指派 || 已指派)数据  控制器
     */
    public function index($workorderstatus = '')
    {
        // 接收ajax请求模糊查询数据
        $searchObj = request()->get();

        // 初始化默认为未指派
        if ($workorderstatus == 3) {
            $where['a.work_order_status'] = ['<','5'];
        }
        if ($workorderstatus == 4) {
            $where['a.work_order_status'] = ['>','4'];
        }

        // 接收当前页码数
        $nowPage = input('get.page') ? input('get.page') : 1;
        // 设置每页显示条数
        $limits = config('pagesize');



        // 查询 的字段
        $field = 'a.order_number,b.username,b.telphone,a.business_id,d.company_name,f.company_name a_name,
                  a.combo_money,c.for_core_time,c.renew_date,a.work_order_status,
                  e.engineers_name,a.remarks,a.order_time,a.work_order_id,b.user_id,c.contract_id';
        // 连表
        $join = [
                 ['rq_customer b', 'b.user_id = a.user_id','LEFT'],                     // 客户表 对应 工单表
                 ['rq_contract c', 'c.contract_id = a.contract_id','LEFT'],             // 合同表 对应 工单表
                 ['rq_operation_info d', 'd.o_id = a.operation_id','LEFT'],             // 运营中心表 对应 工单表
                 ['rq_engineers e', 'e.engineers_id = a.repair_id','LEFT'],             // 工程人员表 对应 工单表
                 ['rq_administrative_info f', 'f.a_id = a.administrative_id','LEFT']    // 行政中心表 对应 工单表
        ];

        // 判断工单类型状态是否有值
        if(!empty($searchObj['status'])){
            // 判断是否移机
            if($searchObj['status'] == 5){
                $where['a.business_id'] = ['in','5,9,10'];
            }else{
                $where['a.business_id'] = $searchObj['status'];
            }
        }

        //合同编号
        if (isset($searchObj['contract_no']) && !empty($searchObj['contract_no'])){
            $where['c.contract_no'] = trim($searchObj['contract_no']);
        }
        //判断用户有没有选择处理状态
        if (!empty($searchObj['workStatus'])) {
          if ($searchObj['workStatus'] == 13){
                $where['a.work_order_status'] = ['in', '9,10,11,12'];
            }else{
                $where['a.work_order_status'] = $searchObj['workStatus'];
            }
        }
        //判断用户有没有选择业务类型
        if (!empty($searchObj['type'])) {
            $where['a.business_id'] = $searchObj['type'];
        }
        // 判断用户有没有输入工单号
        if (!empty($searchObj['order_number'])) {
            $where['a.order_number'] = $searchObj['order_number'];
        }
        // 判断用户有没有输入用户名
        if (!empty($searchObj['username'])) {
            $where['b.username'] = $searchObj['username'];
        }
        // 判断用户有没有输入联系电话
        if (!empty($searchObj['telphone'])) {
            $where['b.telphone'] = $searchObj['telphone'];
        }
        // 判断用户有没有输入工程人员姓名
        if (!empty($searchObj['engineers_name'])) {
            $where['e.engineers_name'] = $searchObj['engineers_name'];
        }
        // 判断用户有没有输入工程编号
        if (!empty($searchObj['engineers_number'])) {
            $where['e.engineers_number'] = $searchObj['engineers_number'];
        }
        // 判断用户有没有输地区搜索  省 ，
        if (!empty($searchObj['province'])) {
            $where['f.province_id'] = $searchObj['province'];
        }
        // 判断用户有没有输地区搜索 市 ，
        if (!empty($searchObj['city'])) {
            $where['f.city_id'] = $searchObj['city'];
        }
        // 判断用户有没有输地区搜索 区，
        if (!empty($searchObj['area'])) {
            $area = $searchObj['area'];
            $where['f.area_id'] = ['like',"%$area%"];
        }
       // 判断用户有没有输开始日期 // 判断用户有没有输结束日期
       if(!empty($searchObj['startTime']) && !empty($searchObj['endTime'])){
           $where['a.order_time'] = ['between', [strtotime($searchObj['startTime']), strtotime($searchObj['endTime'])+(60*60*24-1)]];//终止到当天23:59:59
       }else if(!empty($searchObj['startTime'])){
           $where['a.order_time'] = ['>=',strtotime($searchObj['startTime'])];
       }else if(!empty($searchObj['endTime'])){
           $where['a.order_time'] = ['<=', strtotime($searchObj['endTime'])+(60*60*24-1)];
       }

            // 更新时间
        $startUpdateTime = input('get.startUpdateTime') ? input('get.startUpdateTime') : '';
        $endUpdateTime = input('get.endUpdateTime') ? input('get.endUpdateTime') : '';
        if(!empty($startUpdateTime) && !empty($endUpdateTime)){
            $where['a.update_time'] = ['between time', [strtotime($startUpdateTime),strtotime($endUpdateTime)+(60*60*24)]];
        }
       // 查询未被逻辑删除的数据
       $where['a.is_delete'] = 0;
       // 主表
       $dbName = 'rq_work_order';

        // 调用方法
        $data = self::$workModel->getAll($field,$where,$nowPage,$limits,$dbName,$join);

        // 判断状态码是否为空
        $count = self::$workModel->getCount($where,$dbName,$join);

        // 获取工单类型
        $type = config('workorder_type');
        // 获取工单状态
        $status = config('work_order_status');
        $workType = ['1' => '续费','2' => '换芯','3' => '新装','4' => '拆机','5' => '移机',
            '6' => '维修','7' => '续费+维修','8' => '换芯+维修','9' => '移机(拆)','10' => '移机(装)',
        ];

        // 计算总的页面数
        $allPage = intval(ceil($count / $limits));
        $this->assign('nowPage', $nowPage); //当前页
        $this->assign('allPage', $allPage); //总页数
        $this->assign('count',$count);// 总的条数
        $this->assign('work_order_status',$status);// 工单状态




        // 判断数据是否有值
        if (!empty($data)) {
            // 类型 状态 转换
            foreach ($data as $k=>$v)
            {
                $data[$k]['business_id'] = $workType[$v['business_id']];
                $data[$k]['work_order_status'] = $status[$v['work_order_status']];
                if (strlen($v['for_core_time']) < 5) {
                    $data[$k]['for_core_time'] = '';
                }else{
                    $data[$k]['for_core_time'] = date('Y/m/d', $v['for_core_time']);
                }
                $data[$k]['renew_date'] = $v['renew_date'] ? $v['renew_date'] : '';
                $data[$k]['nowPage'] = $nowPage;
                $data[$k]['allPage'] = $allPage;
                $data[$k]['count'] = $count;
                $data[$k]['who'] = $workorderstatus;    // 未指派已指派标识数
            }
        }
        // 返回
        return $data;

    }

    /**
     * @return mixed|\think\response\Json
     *       渲染未指派工单页面
     */
    public function unassigned()
    {

        $workorderstatus = 3;
        $data = $this->index($workorderstatus);

        // 获取工单类型
        $type = config('workorder_type');
        // 获取工单状态
        $status = config('work_order_status');
        $workType = ['1' => '续费','2' => '换芯','3' => '新装','4' => '拆机','5' => '移机',
            '6' => '维修','7' => '续费+维修','8' => '换芯+维修','9' => '移机(拆)','10' => '移机(装)',
        ];

        // 判断用户是否有值
        if (input('get.page')) {
            return json($data);
        }

        // 模板赋值 数据，类型
        $this->assign(
            [
                'data' => $data,
                'type' => $type,
                'workType' => $workType,
                'status' => $status,
                'workorderstatus' => $workorderstatus
            ]);
        // 调用视图
        return $this->fetch('index');
    }

    /**
     * @return mixed|\think\response\Json
     *       渲染已指派工单页面
     */
    public function assigned()
    {
        $workorderstatus = 4;
        $data = $this->index($workorderstatus);
        // 获取工单类型
        $type = config('workorder_type');
        // 获取工单状态
        $status = config('work_order_status');
        $workType = ['1' => '续费','2' => '换芯','3' => '新装','4' => '拆机','5' => '移机',
            '6' => '维修','7' => '续费+维修','8' => '换芯+维修','9' => '移机(拆)','10' => '移机(装)',
        ];

        // 判断用户是否有值
        if (input('get.page')) {
            return json($data);
        }

        // 模板赋值 数据，类型
        $this->assign(
            [
                'data' => $data,
                'type' => $type,
                'workType' => $workType,
                'status' => $status,
                'workorderstatus' => $workorderstatus
            ]);

        // 调用视图
        return $this->fetch('index');
    }

    /**
     * @param $id
     * @return mixed
     *     渲染工单 详情页面
     */
    public function detail($id)
    {

        // 调用getDetail方法 ， 获取工单详情
        $dataDetail = self::$workModel->getDetail($id);

        // 基本信息
        $basicData = $dataDetail[0];
        // 工单信息
        $workData  = $dataDetail[1];
        $workData[0]['service_address'] = $workData[0]['province'].$workData[0]['city'].$workData[0]['area'].$workData[0]['service_address'];
        $workData[0]['move_address'] = $workData[0]['move_province'].$workData[0]['move_city'].$workData[0]['move_area'].$workData[0]['move_address'];
        // 工单轨迹
        $userData = $dataDetail[2];
        // 设备号
        $equipmentNumber = $dataDetail[3];
        // 配件信息
        $partsData = $dataDetail[4];

        // 处理状态
        $status = config('work_order_status');
        // 类型
        $type = ['1' => '续费','2' => '换芯','3' => '新装','4' => '拆机','5' => '移机',
            '6' => '维修','7' => '续费+维修','8' => '换芯+维修','9' => '移机(拆)','10' => '移机(装)',
        ];
        // 客户性质
        $nature = config('nature');
        // 住房性质
        $housing = config('housing_property');

        // 工单信息数据转换
        foreach ($workData as $k=>$v)
        {
            $workData[$k]['business_id'] = $type[$v['business_id']];
            $workData[$k]['work_order_status'] = $status[$v['work_order_status']];
        }

        // 调用视图将数据赋值给页面
        return $this->fetch('detail',
                [
                    'basicData' => $basicData,
                    'workData' => $workData,
                    'userData' => $userData,
                    'equipmentNumber' => $equipmentNumber,
                    'partsData' => $partsData
                ]);

    }

    /**
     * @return \think\response\Json
     *       获取更多工单轨迹数据
     */
    public function getWorkLog()
    {
        // 接收参数
        $workId = input('get.workid');  // 工单ID
        $page = input('get.page');      // 页码数
        $limits = ($page*5).','.(5);
        $where['work_order_id'] = $workId;   // 工单ID
        $data = self::$workModel->getLast($where, $limits);
        // 判断是否有数据
        if (empty($data)) {
            $data[0]['status'] = 0;
            return json($data);
        }
        foreach ($data as $k => $v){
            $data[$k]['operating_time'] = date('Y年m月d日 H:i:s',$v['operating_time']);
            $data[$k]['page'] = $page + 1;
            $data[$k]['status'] = 1;
        }

        return json($data);
    }

    /**
     * @return \think\response\Json
     *     ajax 异步 工单 批量删除 或 恢复
     */
    public function remove()
    {

        // 获取ajax 请求数据
        $work_order_id = input('')['data'];
        // 删除还是恢复
        $is_delete = input('')['is_delete'];
        // 循环数据 循环删除
        foreach ($work_order_id as $k=>$v)
        {
            // 是on 就退出循环
            if ($v == 'on') {
                continue;
            }

            // 调用方法查询工单数据
            $data = self::$workModel->getOne(array('work_order_id'=>intval($v)));
            // 判断 是否有数据
            if (empty($data)) {
                if ($is_delete == 1) {
                    return json(['status' => 0, 'message' => '删除失败']);
                }else{
                    return json(['status' => 0, 'message' => '还原失败']);
                }
            }
            // 调用 remove方法 进行删除
            $rel = self::$workModel->remove($v,$is_delete);
            // 判断结果 并删除
            if ($rel == false) {
                if ($is_delete == 1) {
                    return json(['status' => 0, 'message' => '删除失败']);
                }else{
                    return json(['status' => 0, 'message' => '还原失败']);
                }
            }

        }
        if ($is_delete == 1) {
            return json(['status' => 1, 'message' => '删除成功']);
        }else{
            return json(['status' => 1, 'message' => '还原成功']);
        }

    }

    /**
     * @return \think\response\Json
     *     ajax  异步修改 工单 处理状态
     */
    public function status()
    {

        $company_name = '总后台';

        // 获取当前登录用户id
        $u_id = session($this->set['db_name'].'uid');
        // 获取当前登录用户名
        $username = session($this->set['db_name'].'username');

        // 接收ajax请求 获取要修改的状态值
        $data = request()->get();

        // 判断参数是否有效
        if (!empty($data)) {
            // 根据工单ID查询数据判断是否为新装
            $curlWhere['work_order_id'] = $data['work_order_id'];
            $curlData = self::$workModel->getOne($curlWhere);

            // 当工单为新装时
            if ($curlData['business_id'] == 3) {
                // 当状态为 12=>'前台已回访，已完成' 时
                if ($data['work_order_status'] == 12) {
                    // 判断是否绑定合同---------------------------
                    // 实例化合同表模型
                    $contractModel = new Contract();
                    $cttWhere['contract_id'] = $curlData['contract_id'];
                    $cttData = $contractModel->selectOne($cttWhere);
                    if (empty($cttData)) {
                        return json(['status' => 0, 'message' => '请绑定合同']);
                    }

                    // 查询当前工单的工程人员
//                    $engineersWhere['engineers_id'] = $curlData['repair_id'];
//                    $engineersData = Db::name('engineers')->where($engineersWhere)->find();
                    //查询当前工单讲解人员
                    if (!empty($curlData['engineers_id'])){
                        $engineersWhere['engineers_id'] = $curlData['engineers_id'];
                        $engineersData = Db::name('engineers')->where($engineersWhere)->find();
                        if (empty($engineersData)){
                            return json(['status' => 0, 'message' => '讲解人（工程人员）不存在']);
                        }
                    }
                    // 查询当前工单的合同信息
                    $contractWhere['contract_id'] = $curlData['contract_id'];
                    $contractData = Db::name('contract')->where($contractWhere)->find();

                    if ($contractData['is_special'] == 1){
                        return json(['status' => 0, 'message' => '特殊合同不能提交到业绩系统']);
                    }

                    //判断是否是商用客户
                    if ($contractData['nature'] == 1){
                        //提交到后台审核
                        if ($curlData['audit_status'] == 1){
                            return json(['status' => 0, 'message' => '审核通过，不能重复提交']);
                        }

                        if ($curlData['audit_status'] != 3){
                            $update_info = Db::table('rq_work_order')->where(['work_order_id'=>$curlData['work_order_id']])->update(['audit_status'=>3]);
                            if ($update_info > 0){
                                return json(['status' => 1, 'message' => '修改成功，等待财务审核']);
                            }else{
                                return json(['status' => 0, 'message' => '修改失败，请稍后再试']);
                            }
                        }

                        // 调用方法
                        $result = self::$workModel->editStatus($data,$u_id,$username,$company_name);
                        if ($result){
                            return json(['status' => 1, 'message' => '修改成功，等待财务审核']);
                        }else{
                            return json(['status' => 0, 'message' => '修改失败，请稍后再试']);
                        }
                    }

                    // 查询当前工单的合同客户
                    $customerWhere['user_id'] = $contractData['user_id'];
                    $customerData = Db::name('customer')->where($customerWhere)->find();
                    // 查询当前工单合同推荐人
                    $userWhere['user_id'] = $contractData['introducer_id'];
                    $userData = Db::name('customer')->where($userWhere)->find();
                    //获取合同的申请人
                    $applicant = Db::name('customer')->where(['user_id'=>$contractData['applicant']])->find();
                    // 当推荐人为员工时
//                    if ($userData['is_entry'] == 1) {
                    if (true) {
                        // 查询当前工单设备数量
                        $contractEquipmentWhere['contract_id'] = $contractData['contract_id'];
                        $contractEquipmentWhere['state'] = 1;
                        $contractEquipmentData = Db::name('contract_equipment')->where($contractEquipmentWhere)->count();

                        // post_data数据
                        $post_data['is_explain'] = $contractData['is_explain'];
                        $post_data['achievement_work_order_number'] = $curlData['order_number'];
                        $post_data['achievement_work_order_type'] = $curlData['business_id'];
                        $post_data['engineers_name'] = !empty($curlData['engineers_id']) ? $engineersData['engineers_name'] : '';
                        //$post_data['engineers_number'] = $contractData['eq_count'];//设备数
                        $post_data['engineers_number'] = !empty($curlData['engineers_id']) ? $engineersData['engineers_number'] : '';//工程人员编号
                        $post_data['contract_number'] = $contractData['contract_no'];
                        $post_data['nature'] = $contractData['nature'];//客户类型
                        $post_data['contract_customer'] = $customerData['username'];
                        $post_data['contract_customer_id_card'] = $customerData['id_card'];

                        $post_data['contract_introducer'] = (!empty($contractData['introducer_id']))?$userData['username']:'';//转介绍人

                        $post_data['applicant'] = $applicant['employee_id'];//申请人（员工编号）

                        //如果转介绍入职了，转介绍就是申请人
                        if ($userData['is_entry'] == 1){
                            $post_data['applicant'] = $userData['employee_id'];
                        }

                        $post_data['equipments_number'] = ($contractData['nature'] == 1)?$contractData['eq_count']:$contractEquipmentData;
                        $post_data['request_time'] = time();

                        //数据加密
                        $key = date('Y')."优".date('m')."合".date("d")."一".date("H")."众";
                        $expiry = 10;
                        $request_data['data'] = $this->dataEncode($post_data,$key,$expiry);
                        // crm业绩系统接口地址
                        $url = config('post_api');
                        // 调用post_request发送请求
                        $curResult = post_request($url ,$request_data);
                        $ApiResult = json_decode($curResult);
                        $rank['contract_no']=$contractData['contract_no'];
                        if ($ApiResult->code == 1){
                            //组装合同等级关系数据
                            $tmp=$ApiResult->data;
                            foreach ($tmp as $k=>$v){
                                $rank[$k]=$v;
                            }
                            if(!isset($rank['apply_id'])&&isset($rank['push_id'])){
                                $rank['apply_id']=$rank['push_id'];
                                unset($rank['push_id']);
                            }if(!isset($rank['apply_name'])&&isset($rank['push_name'])){
                                $rank['apply_name']=$rank['push_name'];
                                unset($rank['push_name']);
                            }
                            if($userData){
                                $rank['push_apply_id']=$userData['employee_id'];
                                $rank['push_apply_name']=$userData['username'];
                            }
                            $res = db('contract_rank')->insert($rank);
                            //家用机直接审核通过
                            Db::table('rq_work_order')->where(['work_order_id'=>$curlData['work_order_id']])->update(['audit_status'=>1]);
                            // 调用方法
                            $result = self::$workModel->editStatus($data,$u_id,$username,$company_name);
                            // 判断结果 并返回json数据
                            if ($result == false) {
                                return json(['status' => 0, 'message' => '修改状态失败']);
                            }
                            return json(['status' => 1, 'message' => '修改状态成功']);
                        }else{
                            return json(['status' => 0, 'message' => $ApiResult->msg]);
                        }


                    }
                    else{

                        // 判断是否绑定合同---------------------------
                        // 实例化合同表模型
                        $contractModel = new Contract();
                        $cttWhere['contract_id'] = $curlData['contract_id'];
                        $cttData = $contractModel->selectOne($cttWhere);
                        if (empty($cttData)) {
                            return json(['status' => 0, 'message' => '请绑定合同']);
                        }

                        // 调用方法
                        $result = self::$workModel->editStatus($data,$u_id,$username,$company_name);
                        // 判断结果 并返回json数据
                        if ($result == false) {
                            return json(['status' => 0, 'message' => '修改状态失败']);
                        }
                        return json(['status' => 1, 'message' => '修改状态成功']);
                    }

                }else{

                    // 调用方法
                    $result = self::$workModel->editStatus($data,$u_id,$username,$company_name);
                    // 判断结果 并返回json数据
                    if ($result == false) {
                        return json(['status' => 0, 'message' => '修改状态失败']);
                    }
                    return json(['status' => 1, 'message' => '修改状态成功']);
                }

            }else{

                // 判断是否走最后一步
                if ($data['work_order_status'] == 12) {
                    // 判断是否绑定合同---------------------------
                    // 实例化合同表模型
                    $contractModel = new Contract();
                    $cttWhere['contract_id'] = $curlData['contract_id'];
                    $cttData = $contractModel->selectOne($cttWhere);
                    if (empty($cttData)) {
                        return json(['status' => 0, 'message' => '请绑定合同']);
                    }
                }

                // 调用方法
                $result = self::$workModel->editStatus($data,$u_id,$username,$company_name);
                // 判断结果 并返回json数据
                if ($result == false) {
                    return json(['status' => 0, 'message' => '修改状态失败']);
                }
                return json(['status' => 1, 'message' => '修改状态成功']);
            }


        }else{
            return json(['status' => 0, 'message' => '参数错误']);
        }

    }

    /**
     * @return mixed|\think\response\Json
     *       渲染 工单 回收站列表
     */
    public function recycle()
    {

        // 接收ajax请求模糊查询数据
        $searchObj = request()->get();

        // 判断是否点击已指派跟未指派
        if (!empty($searchObj['workorderstatus'])) {
            // 未指派
            if ($searchObj['workorderstatus'] == 3) {
                $where['a.work_order_status'] = ['<','4'];
            }
            // 已指派指派
            if ($searchObj['workorderstatus'] == 4) {
                $where['a.work_order_status'] = ['>','3'];
            }
        }


        // 接收当前页码数
        $nowPage = input('get.page') ? input('get.page') : 1;
        // 设置每页显示条数
        $limits = config('pagesize');


        // 查询 的字段
        $field = 'a.order_number,b.username,b.telphone,a.business_id,d.company_name,f.company_name a_name,
                  a.combo_money,c.for_core_time,c.renew_date,a.work_order_status,
                  e.engineers_name,a.remarks,a.order_time,a.work_order_id,b.user_id,c.contract_id';
        // 连表
        $join = [
            ['rq_customer b', 'b.user_id = a.user_id','LEFT'],                     // 客户表 对应 工单表
            ['rq_contract c', 'c.contract_id = a.contract_id','LEFT'],             // 合同表 对应 工单表
            ['rq_operation_info d', 'd.o_id = a.operation_id','LEFT'],             // 运营中心表 对应 工单表
            ['rq_engineers e', 'e.engineers_id = a.repair_id','LEFT'],             // 工程人员表 对应 工单表
            ['rq_administrative_info f', 'f.a_id = a.administrative_id','LEFT']    // 行政中心表 对应 工单表
        ];

        // 判断工单类型状态是否有值
        if(!empty($searchObj['status'])){
            // 判断是否移机
            if($searchObj['status'] == 5){
                $where['a.business_id'] = ['in','5,9,10'];
            }else{
                $where['a.business_id'] = $searchObj['status'];
            }
        }
        //判断用户有没有选择处理状态
        if (!empty($searchObj['workStatus'])) {
            if ($searchObj['workStatus'] == 12) {
                $where['a.work_order_status'] = ['in','5,6,7'];
            }else{
                $where['a.work_order_status'] = $searchObj['workStatus'];
            }
        }
        //判断用户有没有选择业务类型
        if (!empty($searchObj['type'])) {
            $where['a.business_id'] = $searchObj['type'];
        }
        // 判断用户有没有输入工单号
        if (!empty($searchObj['order_number'])) {
            $where['a.order_number'] = $searchObj['order_number'];
        }
        // 判断用户有没有输入用户名
        if (!empty($searchObj['username'])) {
            $where['b.username'] = $searchObj['username'];
        }
        // 判断用户有没有输入联系电话
        if (!empty($searchObj['telphone'])) {
            $where['b.telphone'] = $searchObj['telphone'];
        }
        // 判断用户有没有输入工程人员
        if (!empty($searchObj['engineers_name'])) {
            $where['e.engineers_name'] = $searchObj['engineers_name'];
        }
        // 判断用户有没有输入工程人员编号
        if (!empty($searchObj['engineers_number'])) {
            $where['e.engineers_number'] = $searchObj['engineers_number'];
        }
        // 判断用户有没有输地区搜索  省 ，
        if (!empty($searchObj['province'])) {
            $where['f.province_id'] = $searchObj['province'];
        }
        // 判断用户有没有输地区搜索 市 ，
        if (!empty($searchObj['city'])) {
            $where['f.city_id'] = $searchObj['city'];
        }
        // 判断用户有没有输地区搜索 区，
        if (!empty($searchObj['area'])) {
            $area = $searchObj['area'];
            $where['f.area_id'] = ['like',"%$area%"];
        }
        // 判断用户有没有输开始日期 // 判断用户有没有输结束日期
        if(!empty($searchObj['startTime']) && !empty($searchObj['endTime'])){
            $where['a.order_time'] = ['between', [strtotime($searchObj['startTime']), strtotime($searchObj['endTime'])+(60*60*24-1)]];//终止到当天23:59:59
        }else if(!empty($searchObj['startTime'])){
            $where['a.order_time'] = ['>=',strtotime($searchObj['startTime'])];
        }else if(!empty($searchObj['endTime'])){
            $where['a.order_time'] = ['<=', strtotime($searchObj['endTime'])+(60*60*24-1)];
        }
        // 查询未被逻辑删除的数据
        $where['a.is_delete'] = 1;
        // 主表
        $dbName = 'rq_work_order';


        // 调用方法
        $data = self::$workModel->getAll($field,$where,$nowPage,$limits,$dbName,$join);

        // 判断状态码是否为空
        if (empty($searchObj['status'])) {
            $count = self::$workModel->getCount($where,$dbName,$join);
        }else{
            // 获取查询的数据的count
            $count = count($data);
        }

        // 获取工单类型
        $type = config('workorder_type');
        // 获取工单状态
        $status = config('work_order_status');
        $workType = ['1' => '续费','2' => '换芯','3' => '新装','4' => '拆机','5' => '移机',
            '6' => '维修','7' => '续费+维修','8' => '换芯+维修','9' => '移机(拆)','10' => '移机(装)',
        ];

        // 计算总的页面数
        $allPage = intval(ceil($count / $limits));
        $this->assign('nowPage', $nowPage); //当前页
        $this->assign('allPage', $allPage); //总页数
        $this->assign('count',$count);// 总的条数
        $this->assign('work_order_status',$status);// 总的条数


        // 判断数据是否有值
        if (!empty($data)) {
            // 类型 状态 转换
            foreach ($data as $k=>$v)
            {
                $data[$k]['business_id'] = $workType[$v['business_id']];
                $data[$k]['work_order_status'] = $status[$v['work_order_status']];
                if (strlen($v['for_core_time']) < 5) {
                    $data[$k]['for_core_time'] = '';
                }else{
                    $data[$k]['for_core_time'] = date('Y/m/d', $v['for_core_time']);
                }
                $data[$k]['renew_date'] = $v['renew_date'] ? $v['renew_date'] : '';
                $data[$k]['nowPage'] = $nowPage;
                $data[$k]['allPage'] = $allPage;
                $data[$k]['count'] = $count;
                $data[$k]['who'] = 5;           // 页面标识数
            }
        }

        // 判断用户是否有值
        if (input('get.page')) {
            return json($data);
        }

        // 模板赋值 数据，类型
        $this->assign(
            [
                'data' => $data,
                'type' => $type,
                'workType' => $workType,
                'status' => $status
            ]);
        // 调用视图
        return $this->fetch();

    }


    /**
     * @param $businessid
     * @return false|\PDOStatement|string|\think\Collection
     *       处理  (续费 || 换芯)数据  控制器
     */
    public function renewcore($businessid)
    {

        // 接收ajax请求模糊查询数据
        $searchObj = request()->get();

        // 接收 续费 或 换芯 对应值
        if (!empty($businessid)) {
            $where['a.business_id'] = $businessid;
        }

        // 接收当前页码数
        $nowPage = input('get.page') ? input('get.page') : 1;
        // 设置每页显示条数
        $limits = config('pagesize');

        // 查询 的字段
        $field = 'a.order_number,b.username,b.telphone,a.business_id,d.company_name,f.company_name a_name,
                  a.combo_money,c.for_core_time,c.renew_date,a.work_order_status,
                  e.engineers_name,a.remarks,a.order_time,a.work_order_id,b.user_id,c.contract_id';
        // 连表
        $join = [
            ['rq_customer b', 'b.user_id = a.user_id','LEFT'],                     // 客户表 对应 工单表
            ['rq_contract c', 'c.contract_id = a.contract_id','LEFT'],             // 合同表 对应 工单表
            ['rq_operation_info d', 'd.o_id = a.operation_id','LEFT'],             // 运营中心表 对应 工单表
            ['rq_engineers e', 'e.engineers_id = a.repair_id','LEFT'],             // 工程人员表 对应 工单表
            ['rq_administrative_info f', 'f.a_id = a.administrative_id','LEFT']    // 行政中心表 对应 工单表
        ];

        // 判断工单类型状态是否有值
        if(!empty($searchObj['status'])){
            // 判断是否移机
            if($searchObj['status'] == 5){
                $where['a.business_id'] = ['in','5,9,10'];
            }else{
                $where['a.business_id'] = $searchObj['status'];
            }
        }
        //判断用户有没有选择处理状态
        if (!empty($searchObj['workStatus'])) {
            if ($searchObj['workStatus'] == 12) {
                $where['a.work_order_status'] = ['in','5,6,7'];
            }else{
                $where['a.work_order_status'] = $searchObj['workStatus'];
            }
        }
        //判断用户有没有选择业务类型
        if (!empty($searchObj['type'])) {
            $where['a.business_id'] = $searchObj['type'];
        }
        // 判断用户有没有输入工单号
        if (!empty($searchObj['order_number'])) {
            $where['a.order_number'] = $searchObj['order_number'];
        }
        // 判断用户有没有输入用户名
        if (!empty($searchObj['username'])) {
            $where['b.username'] = $searchObj['username'];
        }
        // 判断用户有没有输入联系电话
        if (!empty($searchObj['telphone'])) {
            $where['b.telphone'] = $searchObj['telphone'];
        }
        // 判断用户有没有输入工程人员
        if (!empty($searchObj['engineers_name'])) {
            $where['e.engineers_name'] = $searchObj['engineers_name'];
        }
        // 判断用户有没有输入工程人员
        if (!empty($searchObj['engineers_number'])) {
            $where['e.engineers_number'] = $searchObj['engineers_number'];
        }
        // 判断用户有没有输地区搜索  省 ，
        if (!empty($searchObj['province'])) {
            $where['f.province_id'] = $searchObj['province'];
        }
        // 判断用户有没有输地区搜索 市 ，
        if (!empty($searchObj['city'])) {
            $where['f.city_id'] = $searchObj['city'];
        }
        // 判断用户有没有输地区搜索 区，
        if (!empty($searchObj['area'])) {
            $area = $searchObj['area'];
            $where['f.area_id'] = ['like',"%$area%"];
        }
        // 判断用户有没有输开始日期 // 判断用户有没有输结束日期
        if(!empty($searchObj['startTime']) && !empty($searchObj['endTime'])){
            $where['a.order_time'] = ['between', [strtotime($searchObj['startTime']), strtotime($searchObj['endTime'])+(60*60*24-1)]];//终止到当天23:59:59
        }else if(!empty($searchObj['startTime'])){
            $where['a.order_time'] = ['>=',strtotime($searchObj['startTime'])];
        }else if(!empty($searchObj['endTime'])){
            $where['a.order_time'] = ['<=', strtotime($searchObj['endTime'])+(60*60*24-1)];
        }
        // 查询未被逻辑删除的数据
        $where['a.is_delete'] = 0;
        // 主表
        $dbName = 'rq_work_order';


        // 调用方法
        $data = self::$workModel->getAll($field,$where,$nowPage,$limits,$dbName,$join);

        // 判断状态码是否为空
        if (empty($searchObj['status'])) {
            $count = self::$workModel->getCount($where,$dbName,$join);
        }else{
            // 获取查询的数据的count
            $count = count($data);
        }

        // 获取工单类型
        $type = config('workorder_type');
        // 获取工单状态
        $status = config('work_order_status');
        $workType = ['1' => '续费','2' => '换芯','3' => '新装','4' => '拆机','5' => '移机',
            '6' => '维修','7' => '续费+维修','8' => '换芯+维修','9' => '移机(拆)','10' => '移机(装)',
        ];

        // 计算总的页面数
        $allPage = intval(ceil($count / $limits));
        $this->assign('nowPage', $nowPage); //当前页
        $this->assign('allPage', $allPage); //总页数
        $this->assign('count',$count);// 总的条数
        $this->assign('work_order_status',$status);// 工单状态


        // 判断数据是否有值
        if (!empty($data)) {
            // 类型 状态 转换
            foreach ($data as $k=>$v)
            {
                $data[$k]['business_id'] = $workType[$v['business_id']];
                $data[$k]['work_order_status'] = $status[$v['work_order_status']];
                if (strlen($v['for_core_time']) < 5) {
                    $data[$k]['for_core_time'] = '';
                }else{
                    $data[$k]['for_core_time'] = date('Y/m/d', $v['for_core_time']);
                }
                $data[$k]['renew_date'] = $v['renew_date'] ? $v['renew_date'] : '';
                $data[$k]['nowPage'] = $nowPage;
                $data[$k]['allPage'] = $allPage;
                $data[$k]['count'] = $count;
                $data[$k]['who'] = $businessid;     // 页面标识数
            }
        }
        // 返回
        return $data;

    }

    /**
     * @return mixed|\think\response\Json
     *       渲染续费页面
     */
    public function renew()
    {
        // 续费对应值
        $businessid = 1;
        // 调用renewcore方法处理数据
        $data = $this->renewcore($businessid);

        // 获取工单类型
        $type = config('workorder_type');
        // 获取工单状态
        $status = config('work_order_status');
        $workType = ['1' => '续费','2' => '换芯','3' => '新装','4' => '拆机','5' => '移机',
            '6' => '维修','7' => '续费+维修','8' => '换芯+维修','9' => '移机(拆)','10' => '移机(装)',
        ];

        // 判断用户是否有值
        if (input('get.page')) {
            return json($data);
        }

        // 模板赋值 数据，类型
        $this->assign(['data' => $data, 'type' => $type, 'workType' => $workType, 'status' => $status, 'businessid' => $businessid]);
        // 调用视图
        return $this->fetch('renewcore');
    }

    /**
     * @return mixed|\think\response\Json
     *       渲染换芯页面
     */
    public function core()
    {
        // 换芯对应值
        $businessid = 2;
        // 调用renewcore 处理数据
        $data = $this->renewcore($businessid);

        // 获取工单类型
        $type = config('workorder_type');
        // 获取工单状态
        $status = config('work_order_status');
        $workType = ['1' => '续费','2' => '换芯','3' => '新装','4' => '拆机','5' => '移机',
            '6' => '维修','7' => '续费+维修','8' => '换芯+维修','9' => '移机(拆)','10' => '移机(装)',
        ];

        // 判断用户是否有值
        if (input('get.page')) {
            return json($data);
        }

        // 模板赋值 数据，类型
        $this->assign(['data' => $data, 'type' => $type, 'workType' => $workType, 'status' => $status, 'businessid' => $businessid]);
        // 调用视图
        return $this->fetch('renewcore');
    }

    /**
     * @return \think\response\Json
     *      根据工单id获取当前工单备注信息
     */
    public function getremarks()
    {
        Cache::clear();
        // 或工单id
        $work_order_id = request()->get();
        // 拼接条件
        $map = ['work_order_id' => $work_order_id['work_order_id']];
        // 实例化工单备注关联表
        $workRemarksModel = new WorkOrderRemarks();
        // 调用getAll方法获取当前工单id的工单备注关联表数据
        $data = $workRemarksModel->getAll($map);

        // 获取工单信息
        $status = self::$workModel->getOne($map);
        if (!empty($data)) {
            // 时间转换
            foreach ($data as $k => $v)
            {
                $v['operating_time'] = date('Y/m/d', $v['operating_time']);
                $v['work_order_status'] = $status['work_order_status'];
            }
        }

        // 返回
        return json($data);

    }

    /**
     * @return \think\response\Json
     *     修改工单 获取用户数据
     */
    public function getuser()
    {
        // 实例化模型 获取所有用户
        $customerModel = new Customer();

        // 接收搜索数据
        $searchObj = request()->get();
        if (!empty($searchObj)) {
            if (!empty($searchObj['username'])) {
                $where['username'] = $searchObj['username'];
            }
            if (!empty($searchObj['telphone'])) {
                $where['telphone'] = $searchObj['telphone'];
            }
            if (!empty($searchObj['id_card'])) {
                $where['id_card'] = $searchObj['id_card'];
            }
        }

        // 获取当前页码数
        $nowPage = input('get.page') ? input('get.page') : 1;
        // 设置每页显示条数
        $limits = config('pagesize');
        // 查询字段
        $field = [
            'telphone,username,id_card,account_status,user_id'
        ];
        // 查询未被逻辑删除的
        $where['is_delete'] = 0;

        // 调用getList获取所有用户
        $data = $customerModel->getAllUser($where,$nowPage,$limits,$field);
        // 计算总的数据
        $count = $customerModel->getCountUser($where);
        // 计算总的页面数
        $allPage = intval(ceil($count / $limits));

        $account_status =  ['1' => '正常', '2' => '冻结'];
        foreach ($data as $k=>$v)
        {
            $data[$k]['account_status'] = $account_status[$v['account_status']];
            $data[$k]['nowPage'] = $nowPage;
            $data[$k]['allPage'] = $allPage;
            $data[$k]['count'] = $count;
        }

        // 返回
        return json($data);

    }



}